package com.hj.javaweb.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Author : hujing
 * @Date: 2025/6/18 13:57
 * @Description:定义一个切面,并定义切入点、前置通知、后置通知、异常通知、环绕通知
 */
@Aspect
@Component
public class LoginAccept {
    
    private final Logger logger = LoggerFactory.getLogger(LoginAccept.class);
    
    // 定义切入点 SampleService中所有的public方法
    @Pointcut("execution(public * com.hj.javaweb.service.SampleService.*(..))")
    public void sampleServiceMethods(){}
    
    // 前置通知
    @Before(value = "sampleServiceMethods()")
    public void before(JoinPoint joinPoint){
        logger.info("before method:"+joinPoint.getSignature().getName());
        logger.info("args:"+ Arrays.toString(joinPoint.getArgs()));
    }
    
    // 后置通知
    @AfterReturning(pointcut = "sampleServiceMethods()",returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
        logger.info("Exiting method:"+joinPoint.getSignature().getName());
        logger.info("result:"+result);
    }
    
    // 异常通知
    @AfterThrowing(pointcut = "sampleServiceMethods()",throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint,Exception ex){
        logger.info("exception in method:"+joinPoint.getSignature().getName());
        logger.error("exception:"+ex.getMessage());
    }
    
    // 环绕通知
    @Around(value = "sampleServiceMethods()")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();//执行目标方法
        long endTime = System.currentTimeMillis();
        logger.info("method execution time:"+(endTime-startTime));
        return result;
    }
    
}
